//引入Koa
const koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const static = require("koa-static");
const cors = require("koa2-cors");
const path = require("path");
const views = require("koa-views");
const koajwt = require("koa-jwt");
const url = require("url");
const catchError = require("./middlewares/catcherror");
const localFilter = require("./middlewares/localFilter");
const app = new koa();
const router = new Router();
const server = require("http").Server(app.callback()); //koa正确姿势
const io = require("socket.io")(server); //核心，实现客户端之间交互通信

app.use(bodyParser());
app.use(static(path.join(__dirname, "public")));
// //session拦截
// app.use(async (ctx, next) => {
//   localFilter(ctx)
//   await next()
// })

app.use(catchError); //处理异常

// app.use(cors());
// 配置 cors 跨域
app.use(
  cors({
    //设置允许来自指定域名请求
    origin: (ctx) => {
      return "*"; // 允许来自所有域名请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //设置所允许的HTTP请求方法
    allowHeaders: ["Content-Type", "Authorization", "Accept"], //设置服务器支持的所有头信息字段
    exposeHeaders: ["WWW-Authenticate", "Server-Authorization"], //设置获取其他自定义字段
  })
);

//公共数据处理
app.use(async (ctx,next)=>{
  ctx.state.userInfo="我是公共数据"
  await next()
})


// 登录处理
// 中间件对401错误进行
app.use(async (ctx, next) => {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = {
        result: {
          code: 401,
          msg: "登录已过期",
          data: err.message,
        },
      };
    } else {
      throw err;
    }
  });
});
const SECRET = "laotie666"; //随意输入

app.use(
  koajwt({ secret: SECRET }).unless({
    // 登录接口不需要验证
    path: [/^\/login/, /^\/$/, /\/socket.io/,/\/favicon/],
  })
);

// app.use(views(__dirname + '/views', {map: {html: 'ejs'}})) 这种方式文件名得写index.html
app.use(views(__dirname + "/view", { extension: "ejs" })); //这种写index.ejs

const routers = require("./routers/index");

for (let key in routers) {
  app.use(routers[key].routes());
}

app.on("error", (err, ctx) => {
  // console.error("server error", err, ctx);
  console.error("server error", err);
});

//加载路由中间件
app.use(router.routes());
app.use(router.allowedMethods());

io.on("connection", (socket) => {
  console.log("连接成功");
  //发送信息
  socket.on("sendMsg", (data) => {
    io.emit("sendAll", data);
  });
  // 用户断开连接的时候

  socket.on("disconnect", () => {});
});

//监听端口
server.listen(3000, () => {
  console.log("runing....");
});
